﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Configuration;
using System.IO;

namespace AliSMS
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        InitFile init = new InitFile();
        AliSMS Send = new AliSMS();
        AppCode app = new AppCode();
        MsSqlHelper mssql = new MsSqlHelper();
        SQLiteHelper sqlite = new SQLiteHelper();

        DataTable dt = new DataTable();

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string code = cbB.SelectedValue.ToString();
            //MessageBox.Show(code);
            
            DataRow[] drArr = dt.Select("TempLateCode='" + code + "'");
            foreach (DataRow dr in drArr)
            {
                DataTable dts = app.DataSource(dr);
                dGV.DataSource = dts;                
                init.DataViewColumn(dGV, "");
                init.AutoSizeColumn(dGV);
            }            
        }

        int number = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {
            number++;
            bW.RunWorkerAsync();
            tSMInfo.Text = "执行间隔：" + init.sendtime + "分钟 执行次数：" + number.ToString() + "次";
        }

        private void btnAutoSend_Click(object sender, EventArgs e)
        {            
            if (timer1.Enabled) {
                timer1.Enabled = false;
                btnAutoSend.Text = "开始自动发送";
            } else {
                timer1.Enabled = true;
                timer1.Interval = 1000*60* init.sendtime;
                btnAutoSend.Text = "停止自动发送";
                bW.CancelAsync();
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;//还原大小   可改成最大化
                this.Activate();
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;
            
            }
        }

        private void 打开主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;//还原大小   可改成最大化
                this.Activate();
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;
            }           
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Form1_SizeChanged事件，效果为最小化窗体时，在系统托盘区域显示程序图标及气球提示：
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;//任务栏
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(3, "注意", "我是一个盾牌图标，我负责发送短信", ToolTipIcon.Info);
            }
            else
            {
                this.ShowInTaskbar = true;//任务栏
                notifyIcon1.Visible = false;
            }             
        }

        private void Main_Load(object sender, EventArgs e)
        {
            DBCreate();

            if (!mssql.getConDBStatus())
            {
                if (MessageBox.Show("数据库链接配置有问题，请检查", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    Application.ExitThread();
                    Application.Exit();
                }
            }

            tSMInfo.Text = "执行间隔：" + init.sendtime + "分钟 执行次数：0次";
            if (init.IsAuto)
            {
                if (timer1.Enabled)
                {
                    timer1.Enabled = false;
                    btnAutoSend.Text = "开始自动发送";
                }
                else
                {
                    timer1.Enabled = true;
                    timer1.Interval = 1000 * 60 * init.sendtime;
                    btnAutoSend.Text = "停止自动发送";
                    this.Activate();
                    this.ShowInTaskbar = true;//任务栏
                    notifyIcon1.Visible = false;
                    this.WindowState = FormWindowState.Minimized;
                }
            }
            dt = sqlite.ExecuteDt("select id,TempLateTitle,TempLateCode,TempLateSMS,QuerySQL,UpdateSQL from [TempLate] where Beactive=1");
            cbB.DataSource = dt;
            cbB.ValueMember = "TempLateCode";
            cbB.DisplayMember = "TempLateTitle";
            if (dt.Rows.Count == 0) { btnQuery.Enabled = false; }
            init.ClearLog();
        } 

        private void bW_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i<dt.Rows.Count; i++)
            {
                DataRow[] drArr = dt.Select("TempLateCode='" + dt.Rows[i]["TempLateCode"] + "'");
                foreach (DataRow dr in drArr)
                {
                    app.SendData(dr);
                }
            }            
        }

        private void bW_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            init.WriteLog(Convert.ToString(e.ProgressPercentage), false);
        }

        private void bW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                init.WriteLog(e.ToString(), true);
                return;
            }
            if (!e.Cancelled)
                init.WriteLog(e.Cancelled.ToString(), false);
            else
                init.WriteLog(e.Result.ToString(), false);
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormTemplateInfo info = new FormTemplateInfo();
            info.ShowDialog();
        }

        private void dGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            groupBox2.Text ="发送内容，共计 "+ dGV.Rows.Count.ToString()+" 条";
        }

        private void dGV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush brush = new SolidBrush(dGV.RowHeadersDefaultCellStyle.ForeColor))
            {
                string s = (e.RowIndex + 1).ToString();
                e.Graphics.DrawString(s, e.InheritedRowStyle.Font, brush, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
            }
        }


        private void DBCreate()
        {
            try
            {
                string dbFile = @"Data.db";
                if (!File.Exists(dbFile))
                {
                    System.Data.SQLite.SQLiteConnection.CreateFile(dbFile);
                    string sql = " create table if not exists TempLate( "
                               + " id integer not null default null collate binary primary key autoincrement, "
                               + " TempLateTitle text, "
                               + " TempLateCode text, "
                               + " TempLateSMS text, "
                               + " QuerySQL text, "
                               + " UpdateSQL text, "
                               + " Beactive integer"
                               + " );"
                               + " create table if not exists fld( "
                               + " id integer not null primary key autoincrement,"
                               + " fdname text, "
                               + " chnname text "
                               + " );";
                    sqlite.ExecuteSql(sql);
                    sql = " insert into fld(fdname,chnname)values('djbh','单据编号'); "
                        + " insert into fld(fdname,chnname)values('tel','电话号码'); "
                        + " insert into fld(fdname,chnname)values('templatetitle','模板名称'); "
                        + " insert into fld(fdname,chnname)values('templatecode','模板代码'); "
                        + " insert into fld(fdname,chnname)values('beactive','是否活动'); "
                        + " insert into fld(fdname,chnname)values('rq','日期'); ";
                    sqlite.ExecuteSql(sql);
                }
            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(), true);
            }
        }
    }
}
